<template>
  <div id="map-container" :style="{'width':width+'px','height':height+'px'}">

  </div>
</template>

<script>
  export default {
    name: "coordinate",
    props:{
      address:{
        type:String,
        default:''
      },
      width:{
        type:Number,
        default:400
      },
      height:{
        type:Number,
        default:400
      },
      center:{
          type:Array,
          default:[]
      }
    },
    watch:{
      address:function (value,oldValue) {
        if(value != null && value !=''){
          if(this.geocoder == null) this.init();
          this.codeAddress(value);
        }
      }
    },
    data(){
      return{
        geocoder:null,
        map:null,
        marker:null,
        position:{
          lat:'',
          lng:''
        }
      }
    },
    methods:{
      init() {
        let center = this.center || [35.416431,119.526909]
        center = new qq.maps.LatLng(center[0],center[1]);
        let map = new qq.maps.Map(document.querySelector('#map-container'),{
          center: center,
          zoom: 15
        });
        const that = this;
        //调用地址解析类
        this.geocoder = new qq.maps.Geocoder({
          complete : function(result){
            map.setCenter(result.detail.location);
            let marker = that.marker;
            if(marker == null) {
                that.marker = new qq.maps.Marker({
                    map: map,
                    draggable: true,
                    position: result.detail.location
                });
                marker = that.marker;
            }else{
                marker.setPosition(result.detail.location);
            }
              qq.maps.event.addListener(marker,'dragend',function() {
                  let position = marker.getPosition();
                  map.setCenter(position);
                  that.position = position;
                  console.log("==position===>",that.position);
              });
            console.log("==position===>",that.position);
            that.position.lat = marker.position.lat;
            that.position.lng = marker.position.lng;
            that.$emit("getLocation",that.position)
          }
        });
        this.geocoder.getLocation("日照市政府");
        this.map = map;
      },
      codeAddress(address) {
        //通过getLocation();方法获取位置信息值
        this.geocoder.getLocation(address)
      }
    },
    mounted(){
      this.init();
    }
  }
</script>

<style scoped>

</style>